const axios = require('axios');
const { Base64 } = require('js-base64');  // 引入 Base64 模块
const { Buffer } = require('buffer');
const AK = "qBXuYUA7HKE2J4lRPPd5Im28";
const SK = "Qut3YjU6uwZN9f61YMnFwoVBobVm5kMm";
/**
 * 获取图片的Base64编码
 * @param {string} imagePath 图片的URL或本地路径
 * @returns {Promise<string>} 返回Base64编码的图片
 */
async function getImageBase64(imagePath) {
    try {
        let buffer;
        const response = await axios.get(imagePath, { responseType: 'arraybuffer' });
        buffer = Buffer.from(response.data, 'binary');
       
        return Base64.encode(buffer);  // 将二进制数据转换为Base64

    } catch (error) {
        throw new Error('Failed to fetch or convert image to Base64: ' + error.message);
    }
}

/**
 * 获取 Access Token
 * @returns {Promise<string>} 返回 Access Token
 */
async function getAccessToken() {
    const options = {
        method: 'POST',
        url: `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${AK}&client_secret=${SK}`,
    };

    try {
        const res = await axios(options);
        return res.data.access_token;
    } catch (error) {
        throw new Error('Failed to get access token: ' + error.message);
    }
}

/**
 * 进行人脸比对
 * @param {string} imagePath 图片的URL或本地路径
 * @returns {Promise<object>} 返回百度 API 返回的比对结果
 */
async function matchFace(imagePath,imagePath2) {
    try {
        const base64Image = await getImageBase64(imagePath);
        const base64Image1 = await getImageBase64(imagePath2);
        const options = {
            method: 'POST',
            url: `https://aip.baidubce.com/rest/2.0/face/v3/match?access_token=${await getAccessToken()}`,
            headers: {
                'Content-Type': 'application/json',
            },
            data: JSON.stringify([
                {
                    'image': base64Image,
                    'image_type': 'BASE64',
                },
                {
                    'image': base64Image1,
                    'image_type': 'BASE64',
                },
            ]),
        };

        const response = await axios(options);
        // return response.data;
        console.log(response.data,7777);
        
    } catch (error) {
        throw new Error('Error during face matching: ' + error.message);
    }
}

module.exports = {
    matchFace,
};
// matchFace('https://static.wktline.com/avatar/ce3d25e532345cbb820d8715c748719d.jpg','https://static.wktline.com/avatar/c55c794cda2a89e4d3fb46b155adfbd0.jpg')
